#! /usr/bin/env python
#coding=utf-8
import models
import widgets
import utils

from web import form

import os
base_path = os.path.abspath(os.path.dirname(__file__))
render_html = utils.render(base_path)


class RecentThings(widgets.WidgetBase):

    @utils.send_to(render_html, 'recent.html')
    def render(self):
        data = self.get_data()

        if data:
            num_entries = utils.safeint(data.get('entries_to_show', '5'))
            num_comments = utils.safeint(data.get('comments_to_show', '5'))
        else:
            num_entries = 5
            num_comments = 5

        entries, discard = models.Entry.get_posts(num=num_entries)
        comments, discard = models.Comment.get_items(num=num_comments)

        return dict(entries=entries, comments=comments)

    def customize_form(self):
        def v(x):
            x = utils.safeint(x)
            return ((x >= 1) and (x <= 20))


        data = self.get_data()
        if data:
            cform = form.Form(
                form.Textbox('entries_to_show', form.notnull,
                            form.regexp('\d+', 'Must be a digit'),
                            form.Validator('Range: 1~20', v),
                            description='Entries to show',
                            value=data['entries_to_show'], size=16, maxlength=2),
                form.Textbox('comments_to_show', form.notnull,
                            form.regexp('\d+', 'Must be a digit'),
                            form.Validator('Range: 1~20', v),
                            description='Comments to show',
                            value=data['comments_to_show'], size=16, maxlength=2)
                )
        else:
            cform = form.Form(
                form.Textbox('entries_to_show', form.notnull,
                            form.regexp('\d+', 'Must be a digit'),
                            form.Validator('Range: 1~20', v),
                            description='Entries to show',
                            value=5, size=16, maxlength=2),
                form.Textbox('comments_to_show', form.notnull,
                            form.regexp('\d+', 'Must be a digit'),
                            form.Validator('Range: 1~20', v),
                            description='Comments to show',
                            value=5, size=16, maxlength=2)
                )

        return cform

widgets.add_widget(RecentThings())


class CustomHtml(widgets.WidgetBase):

    def render(self):
        data = self.get_data()
        if data:
            return data.get('custom_html', '')
        return ''

    def customize_form(self):
        data = self.get_data()
        if data:
            return form.Form(
                        form.Textarea('custom_html', description='Custom Html',
                        rows='15', cols='60', value=data.get('custom_html')))
        else:
            return form.Form(
                        form.Textarea('custom_html', description='Custom Html',
                        rows='15', cols='60'))

widgets.add_widget(CustomHtml())


class TagCloud(widgets.WidgetBase):

    @utils.send_to(render_html, 'tags.html')
    def render(self):
        return dict(tags=models.Tag.all())

widgets.add_widget(TagCloud())

class PageList(widgets.WidgetBase):

    @utils.send_to(render_html, 'pagelist.html')
    def render(self):
        return dict(pages=models.get_pages())

widgets.add_widget(PageList())

class Links(widgets.WidgetBase):

    @utils.send_to(render_html, 'links.html')
    def render(self):
        data = self.get_data()
        if data:
            return dict(links=self._get_links(data.get('links')))
        return dict(links=None)

    def customize_form(self):
        data = self.get_data()
        if data:
            return form.Form(
                form.Textarea('links', description='Links',
                              rows='15', cols='60', value=data.get('links')))
        else:
            return form.Form(
                form.Textarea('links', description='Links',
                              rows='15', cols='60'))

    def _get_links(self, lines):
        """parsing individual links from multiline data"""
        
        links = []
        for line in lines.splitlines():
            if not line:
                continue

            # incorrect lines are just ignored,
            # and parsing continues.
            try:
                text, href = line.split(',')
                links.append(dict(text=text, href=href))
            except ValueError:
                pass
        return links

widgets.add_widget(Links())
